<script setup lang="ts">
	import { getCurrentInstance, ref } from 'vue'
	import axios from 'axios'

	import type { UploadProps, UploadUserFile } from 'element-plus'
	import { ElMessage, ElMessageBox } from 'element-plus'
	import { ElLoading } from 'element-plus'
	import useUserStore from '@/store/modules/user'
	import { createDirectUploadTask, createMultipartUploadV2Task, FileData } from 'qiniu-js';
	import userApi from '@/api/modules/users/user.ts'

	const loadicon = new URL('@/assets/images/loadicon.gif', import.meta.url).href
	const fullscreenLoading = ref(false)
	const props = withDefaults(
		defineProps<{
			action : UploadProps['action']
			headers ?: any
			data ?: UploadProps['data']
			name ?: UploadProps['name']
			size ?: number
			max ?: number
			files ?: UploadUserFile[]
			notip ?: boolean
			ext ?: string[]
			dirname ?: string
			code ?: string
			typename ?: string
			fileurl ?: string
			filetype ?: string
			urlboxwidth ?: string
		}>(),
		{
			name: 'file',
			size: 1000,
			max: 1,
			// action: `${import.meta.env.VITE_APP_API_BASEURL}Upload/QiniuUpload`,
			action: `${import.meta.env.VITE_APP_API_BASEURL}Upload/QiniuUpload`,
			headers: {
				Authorization: `Bearer ${useUserStore().token}`,
			},
			files: () => [],
			notip: false,
			ext: () => ['mp4', 'MP4'],
			dirname: 'file', // 上传类型
			code: '', // 上传目录code
			typename: '文件上传',
			fileurl: '',
			filetype: '',
			urlboxwidth: '100%'
		},
	)
	const emits = defineEmits<{
		'onSuccess' : [
			res: any,
		]
		'onProgress' : [
			res: any,
			file: UploadUserFile,
			fileList: UploadUserFile[],
		]
	}>()
	// const emits = defineEmits<{
	//   'onSuccess': [
	//     res: any,
	//     file: UploadUserFile,
	//     fileList: UploadUserFile[],
	//   ]
	//   'onProgress': [
	//     res: any,
	//     file: UploadUserFile,
	//     fileList: UploadUserFile[],
	//   ]
	// }>()

	const upload : any = ref('')
	const files : any = ref([])
	const filelist : any = ref([])
	const vodeofile : any = ref('')
	const filetype : any = ref('')
	const dialogVisible : any = ref(false)


	const fileData : FileData = { type: 'string', data: 'content' }
	const percent : any = ref(false)
	const percentnum : any = ref(0)
	const form : any = ref({})


	// const { pictureEcho, pictureType } = getCurrentInstance()!.appContext.config.globalProperties.$tools() // 引入自定义挂载公共方法
	defineOptions({
		name: 'FileUpload',
	})
	const baseurl : any = ref(`${import.meta.env.VITE_APP_API_BASEURLIMG}`)

	const beforeUpload : UploadProps['beforeUpload'] = (file : any) => {
		const fileName = file.name.split('.')
		const fileExt = fileName.at(-1) ?? ''
		const isTypeOk = props.ext.includes(fileExt)
		const isSizeOk = file.size / 1024 / 1024 < props.size
		if (!isTypeOk) {
			ElMessage.error(`上传文件只支持 ${props.ext.join(' / ')} 格式！`)
		}
		if (!isSizeOk) {
			ElMessage.error(`上传文件大小不能超过 ${props.size}MB！`)
		}
		return isTypeOk && isSizeOk
	}

	const onExceed : UploadProps['onExceed'] = (files : any, fileList : any) => {
		console.log(files, fileList, 'files: any, fileList')
		ElMessage.warning('文件上传超过限制')
	}
	watch(() => props.fileurl, (val : any) => {
		filelist.value = []
		files.value = []
		if (props.filetype && props.fileurl) {
			console.log(val, 'valvalval')
			filelist.value.push({ ext: props.filetype, url: val[0] })
			files.value.push({ ext: props.filetype, url: val[0] })
		}

	}, {
		immediate: true,
		deep: true,
	})



	// 自定义上传
	async function httpRequest(file : any) {
		// if (pictureType(props.dirname) === false) {
		// 	ElMessage.error('未配置图片上传参数项')
		// 	return false
		// }
		console.log(file, 'filefilefilefile')
		// if (Math.floor(file.file.size / 1000000) > 4) {
		// 	console.log('大于30')
		// 	const token : any = await qiniu_token(file)
		// 	qiniu_uploadFile(file, token)
		// }
		const token : any = await qiniu_token(file)
		qiniu_uploadFile(file, token)
		// return
		// const fd = new FormData()
		// // fd.append('dirname', !props.code ? pictureType(props.dirname) : `${pictureType(props.dirname)}/${props.code}`)// 传参数

		// fd.append('file', file.file)// 传文件
		// // const loadingInstance = ElLoading.service({
		// // 	lock: true,
		// // 	text: 'Loading',
		// // 	background: 'rgba(0, 0, 0, 0.7)',
		// // })
		// fullscreenLoading.value = true
		// const res = await axios({
		// 	method: 'POST',
		// 	url: props.action,
		// 	data: fd,
		// 	headers: props.headers,
		// })
		// console.log('ImagesUpload', res.data.data)//
		// if (res) {
		// 	fullscreenLoading.value = false
		// 	console.log(res.data, 'files')
		// 	// if (res.data.data.url === '/') {
		// 	// 	ElMessage.error(`上传资源名称已被占用，请修改名称后重新上传`)
		// 	// } else {
		// 	// 	filelist.value.push(res.data.data)
		// 	// 	emits('onSuccess', filelist.value)
		// 	// }
		// 	// filelist.value.push({ ext: 'mp4', url: res.data.data.url })
		// 	emits('onSuccess', [res.data.data.url])


		// } else {
		// 	fullscreenLoading.value = false
		// }
		// console.log(filelist.value, '自定义上传')//
	}

	function qiniu_uploadFile(file : any, token : any) {
		console.log(file, token, 'qiniu_uploadFile') //z这里拿的文件和token
		// const timestamp = Math.floor(Date.now() / 1000);
		// console.log(timestamp);
		// const fileData : FileData = { type: 'file', data: file.file, filename: file.name + ('1111') }
		const fileData : FileData = { type: 'file', data: file.file }
		let config = {
			useCdnDomain: true,
			region: 'z2', // 根据实际地区选择
			retryCount: 3, //上传自动重试次数  默认3次
			tokenProvider: () => {
				return Promise.resolve(token)
			},
		};
		// if (Math.floor(file.file.size / 1000000) > 0) {

		const uploadTask = createMultipartUploadV2Task(fileData, config);
		console.log(uploadTask, 'uploadTask 1')

		percent.value = true
		// 设置进度回调函数
		uploadTask.onProgress((progress : any, context : any) => {
			// 处理进度回调
			// console.log(progress, context, progress.percent, 'context123')
			percentnum.value = Math.round((((progress.percent * 100) - 75) * 4 || 0))
			console.log(progress, context, progress.percent, percentnum.value, 'context123')
		});

		// 设置完成回调函数
		uploadTask.onComplete((result : any, context : any) => {
			// 处理完成回调
			console.log(JSON.parse(result), context, '设置完成回调函数')
			percentnum.value = 100
			let newResult = JSON.parse(result)
			// if (!form.value.name) {
			// 	form.value.name = file.name
			// }
			// form.value.file = newResult.key
			console.log(newResult, 'newResultnewResult')
			emits('onSuccess', ['/' + newResult.key])
			// console.log(form.value, 'that.form')
			setTimeout(() => {
				percent.value = false
				ElMessage.success(`资源上传成功`)
				percentnum.value = 0
			}, 500)
		});

		// 设置错误回调函数
		uploadTask.onError((error : any, context : any) => {
			percent.value = 0
			console.log(error, context, '设置错误回调函数')
			percent.value = false
			ElMessageBox.alert('文件上传失败，请联系管理员', '提示', {
				callback: (action : any) => { },
			})

		});

		uploadTask.start()
		// } else {
		// 	const uploadTask = createDirectUploadTask(fileData, config);
		// }
		// createMultipartUploadV2Task(fileData, config).start()
		// 	.then((result : any) => {
		// 		// 处理任务完成结果
		// 	})
		// 	.catch((error : any) => {
		// 		// 处理任务启动失败错误
		// 	});
	}

	// 获取7牛token
	function qiniu_token(file : any) {
		console.log(file)
		return new Promise((resolve : any, reject : any) => {
			userApi.getToken({
				ext: file.file.name.substring(file.file.name.lastIndexOf('.') + 1)
			}).then((res : any) => {
				console.log(res, 'resres')
				resolve(res.token)
			}).catch((err : any) => {
				ElMessageBox.alert('七牛token验证失败，请联系管理员', '提示', {
					callback: (action : any) => { },
				})
				reject(err)
			})
		});
	}

	function remive(j : any) {
		console.log(upload.value.clearFiles, 'files')
		if (props.max === 1) {
			filelist.value.splice(j, 1)
			upload.value.clearFiles()
		}
		else {
			filelist.value.splice(j, 1)
		}
		emits('onSuccess', filelist.value)
	}
	function onPreview(e : any) {
		vodeofile.value = baseurl.value + e
		console.log(vodeofile.value, 'vodeofile.value')
		dialogVisible.value = true
	}
	function onPreviewFile(e : any, type : any) {
		console.log(e, 'kljklkl')
		dialogVisible.value = false
		vodeofile.value = ""
		filetype.value = type
		setTimeout(() => {
			if (type === 'mp3' || type === 'mp4' || type === 'png' || type === 'jpg') {
				vodeofile.value = baseurl.value + e
				dialogVisible.value = true
			} else {
				vodeofile.value = baseurl.value + e
				window.open(vodeofile.value);
			}
		}, 30)

		console.log(vodeofile.value, 'vodeofile.value')
	}
	function beforeRemove(file : any, fileList : any) {
		console.log(file, fileList, 'fileList')
	}
	const onSuccess : UploadProps['onSuccess'] = (res : any, file : any, fileList : any) => {
		// emits('onSuccess', res, file, fileList)
		// emits('onSuccess', res)
	}
	const onProgress : UploadProps['onProgress'] = (res : any, file : any, fileList : any) => {
		console.log('；乐扣乐扣')
		emits('onProgress', res, file, fileList)
	}

	function trimmedPath(path : any) {
		// 从路径末尾开始查找最后一个斜杠的位置
		const lastSlashIndex = path.lastIndexOf('/');
		// 如果末尾有斜杠，则从最后一个斜杠后面的位置开始截取
		// 否则，直接截取从字符串开始到末尾的部分
		return lastSlashIndex !== -1 ? path.substring(lastSlashIndex + 1) : path;
	}
	function closeFiles() {
		console.log('jkjklhk')
		vodeofile.value = ""
	}
	function closeLoad() {
		fullscreenLoading.value = false
	}
	function closepercent() {
		percent.value = false
		percentnum.value = 0

	}
</script>

<template>

	<el-upload ref="upload" :headers="headers" :action="action" :data="data" :name="name" :before-upload="beforeUpload"
		:on-exceed="onExceed" :on-success="onSuccess" :on-progress="onProgress" :http-request="httpRequest"
		:file-list="files" :show-file-list="false" :limit="max" :on-preview="onPreview">
		<div class="slot">
			<el-button type="primary">
				<svg-icon name="ep:upload-filled" class="el-icon--upload" />{{ typename }}
			</el-button>

			<!-- <div class="el-upload__text">
        将文件拖到此处，或<em>点击上传</em>
      </div> -->
		</div>

		<template #tip>
			<div v-if="!notip" class="el-upload__tip mb-2">
				<div style="display: inline-block;">
					<el-alert :title="`上传文件支持 ${ext.join(' / ')} 格式，单个文件大小不超过 ${size}MB，且文件数量不超过 ${max} 个`" type="info"
						show-icon :closable="false" />
				</div>
			</div>
		</template>
	</el-upload>
	<div v-for="(item, index) in filelist" :key="index"
		style="padding: 3px; display: flex; justify-content: start; line-height: 24px; background-color: #dce9f5;">
		<div class="flex jcc aic">
			<svg-icon name="ep:edit" />
		</div>
		<div :style="{width:props.urlboxwidth}" class="overflow-text" style="margin: 0 16px 0 6px;cursor: pointer;"
			@click="onPreviewFile(item.url,item.ext)">
			<!-- {{ trimmedPath(item.url) }} -->
			{{ trimmedPath(item.url) }}
		</div>
		<div class="flex jcc aic" style="cursor: pointer;" @click="remive(index)">
			<svg-icon name="ep:close" />
		</div>
	</div>
	<el-dialog :z-index="9999" v-model="dialogVisible"
		:title="filetype==='mp3'?'音频':filetype==='mp4'?'视频':(filetype==='png' || filetype==='jpg')?'图片':''"
		width="600px" @close="closeFiles">
		<div v-if="vodeofile && filetype==='mp4'" style="width: 600px;height: 400px;">
			<video style="width: 93%;height: 100%;" autoplay controls :src="vodeofile" />
		</div>
		<div v-if="vodeofile && (filetype==='png' || filetype==='jpg')" style="width: 600px;height: 400px;">
			<img :src="vodeofile" style="width:96%;height:88%;">
		</div>
		<div v-if="vodeofile && filetype==='mp3'" class="flex justify-center items-center"
			style="width: 600px;height: 200px;">
			<audio ref="audioPlayer" controls>
				<source :src="vodeofile" type="audio/mpeg">
				您的浏览器不支持 audio 元素。
			</audio>
		</div>
	</el-dialog>
	<!-- -->
	<div v-if="percent" class="fixed demo-progress w-130 bg-[#fff]  top-50% left-50% "
		style="transform: translate(-50%,-50%); border-radius: 8px; box-shadow: 0px 0px 8px 0px #999; z-index:99999;">
		<!-- <div class="w-full text-end pr-4 pt-4 font-size-6 cursor-pointer" @click="closepercent">
			<svg-icon name="ep:close" />
		</div> -->
		<div class="w-full d-c flex justify-center items-center h-40  py-2 h-16" style=" ">
			<el-progress :width="500" striped striped-flow :text-inside="true" :stroke-width="24"
				:percentage="percentnum" status="success" />
			<div>
				<div class="my-4 c-[#67c23a]" v-if="percentnum>0">上传中...</div>
				<div class="my-4 c-[#e67c28]" v-else>正在解析文件流...</div>
			</div>
		</div>

	</div>
	<!-- 上传时的加载遮罩层 -->
	<!-- <div v-if="fullscreenLoading" class="loading-mask">
		<div class="flex justify-center items-center d-c ">
			<div class=" c-[#409eff]">
				<img class="w-5 h-5" :src="loadicon" alt>
			</div>
			<div class="my-4 c-[#409eff]">上传中...</div>
			<div style="position: fixed; top:60px;right:60px; z-index:1000000;  border-radius: 50%; background-color: rgba(255, 255, 255, 0.8);"
				class="w-16 h-16 flex justify-center items-center font-size-10 cursor-pointer c-[#333]"
				@click="closeLoad">
				<svg-icon name="ep:close" />
			</div>
		</div>
	</div> -->
</template>

<style lang="scss" scoped>
	.loading-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.7);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 2000;
		/* 确保在el-loading之上 */
	}

	.el-loading {
		position: relative;
	}

	.el-loading .el-button {
		position: absolute;
		top: 10px;
		right: 10px;
	}

	.demo-progress .el-progress--line {
		margin-bottom: 15px;
		width: 450px;
		height: 30px;
	}

	.overflow-text {
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	:deep(.el-upload.is-drag) {
		display: inline-block;

		.el-upload-dragger {
			padding: 0;
		}

		&.is-dragover {
			border-width: 1px;
		}

		.slot {
			width: 300px;
			padding: 40px 0;
		}
	}
</style>